package cn.charmaine.org.service.impl;

import cn.charmaine.basic.Exception.CustomException;
import cn.charmaine.basic.util.BaiduAuditUtils;
import cn.charmaine.basic.util.MD5Utils;
import cn.charmaine.basic.util.StrUtils;
import cn.charmaine.org.domain.Employee;
import cn.charmaine.org.domain.Logininfo;
import cn.charmaine.org.domain.Shop;
import cn.charmaine.org.domain.ShopAuditLog;
import cn.charmaine.org.mapper.IEmployeeMapper;
import cn.charmaine.org.mapper.LogininfoMapper;
import cn.charmaine.org.mapper.ShopAuditLogMapper;
import cn.charmaine.org.mapper.ShopMapper;
import cn.charmaine.org.service.IShopService;
import cn.charmaine.basic.base.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.mail.javamail.JavaMailSender;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xmy
 * @since 2022-07-05
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private IEmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;//发送邮件

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
     * 1.校验空参数
     * 2.校验店铺是否存在
     * 3.员工是否存在
     * @param shop
     */
    @Override
    @Transactional
    public void settlement(Shop shop) {
        //1.校验空参数
        if(StringUtils.isEmpty(shop.getName())){
            throw new CustomException("店铺名称不可为空！");
        }

        //2.校验店铺是否存在
        Shop shop1 = shopMapper.selectByName(shop.getName());
        if(shop1 != null){
            throw new CustomException("店铺已注册，请确认信息!");
        }

        if(!BaiduAuditUtils.TextCensor(shop.getName())){
            throw new CustomException("店铺已注册，请确认信息!");
        }

        //3.员工是否存在
        Employee admin = employeeMapper.selectByUsername(shop.getAdmin().getUsername());
        if(admin != null){
            throw new CustomException("员工已注册，请确认信息!");
        }

        //保存（先保存员工再保存店铺）
        //保存员工
        Employee employee = shop.getAdmin();
        if(employee == null){
            throw new CustomException("参数异常");
        }
        if (StringUtils.isEmpty(employee.getUsername()) ||
                StringUtils.isEmpty(employee.getEmail()) ||
                StringUtils.isEmpty(employee.getPhone()) ||
                StringUtils.isEmpty(employee.getPassword())
        ) {
            throw new CustomException("参数异常！");
        }
        //用工具类生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        //给密码加密
        String password = MD5Utils.encrypByMd5(employee.getPassword()+ salt);

        //先设置默认值
        Logininfo logininfo = dto2Logininfo(employee,salt,password);
        Employee emp = logininfo2emp(logininfo);
        //保存logininfo
        logininfoMapper.insert(logininfo);
        //保存员工
        employeeMapper.insert(emp);
        //保存店铺
        shopMapper.insert(shop);

        //更新员工表的店铺id
        //Employee admin1 = shop.getAdmin();
        emp.setShopId(shop.getId());//shop添加时，主键自增返回
        emp.setLogininfoId(logininfo.getId());//返回loginfor的主键
        employeeMapper.update(emp);
    }

    private Employee logininfo2emp(Logininfo logininfo) {
        Employee emp = new Employee();
        BeanUtils.copyProperties(logininfo,emp);
        emp.setState(1);
        return emp;
    }


    private Logininfo dto2Logininfo(Employee employee,String salt,String password) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);

        logininfo.setSalt(salt);
        logininfo.setPassword(password);

        logininfo.setType(0);
        logininfo.setDisable(1);
        return logininfo;
    }


    /**
     * 审核通过
     * @param shopAuditLog
     */
    @Override
    @Transactional
    public void auditPass(ShopAuditLog shopAuditLog) {
        //1.保存审核日志
        shopAuditLogMapper.insert(shopAuditLog);
        //2.修改店铺状态
        Shop shop = shopMapper.selectById(shopAuditLog.getShopId());
        if(shop == null){
            throw new CustomException("数据异常！");
        }
        //设置店铺状态为审核通过
        shop.setState(2);
        //更新店铺信息
        shopMapper.update(shop);
        //3.发送邮件
        //创建邮件对象
        /*SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom("1798620237@qq.com");//发送人
        smm.setTo("1798620237@qq.com");//收件人
        smm.setSubject("今晚打老虎");//邮件主题
        smm.setText("宝塔镇河妖");//邮件内容
        javaMailSender.send(smm);//发送邮件*/
    }

    /**
     * 驳回
     * @param shopAuditLog
     */
    @Override
    @Transactional
    public void auditReject(ShopAuditLog shopAuditLog) {
        //1.保存审核日志
        shopAuditLogMapper.insert(shopAuditLog);
        //2.修改店铺状态
        Shop shop = shopMapper.selectById(shopAuditLog.getShopId());
        if(shop == null){
            throw new CustomException("数据异常！");
        }
        //设置状态
        shop.setState(4);
        //查询管理员，放入店铺，不然admin_id为空
        Employee admin = employeeMapper.selectById(shop.getAdmin_id());
        shop.setAdmin(admin);
        shopMapper.update(shop);
        //发送邮件
        //创建邮件对象
        SimpleMailMessage smm = new SimpleMailMessage();
        smm.setFrom("1798620237@qq.com");//发送人
        Employee employee = employeeMapper.selectById(shop.getAdmin_id());
        if(employee == null){
            throw new CustomException("数据异常！");
        }
        /*smm.setTo(employee.getEmail());//收件人
        smm.setSubject("数据异常驳回");//邮件主题
        smm.setText("请点击链接修改数据：http://192.168.60.95:8081/#/register?id="+shop.getId());//邮件内容
        javaMailSender.send(smm);//发送邮件*/
    }

    @Override
    public List<Long> statistics() {
        return shopMapper.statistics();
    }
}
